const { getList, getDetail, publish, update, del } = require('../controller/item')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { checkLogin, checkAuthor } = require('../utils')

module.exports = async (req, res) => {

  // 获取项目列表
  if (req.method === 'GET' && req.path === '/api/item/list') {
    try {
      let result = await getList()
      return new SuccessModel(result.reverse(), '获取成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 获取后台项目列表
  if (req.method === 'POST' && req.path === '/api/item/list') {
    try {
      let result = await getList(req.body.author)
      return new SuccessModel(result.reverse(), '获取成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 获取项目详情
  if (req.method === 'GET' && req.path === '/api/item/detail') {
    try {
      let result = await getDetail(req.query)
      return new SuccessModel(result, '获取成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 新建项目
  if (req.method === 'POST' && req.path === '/api/item/publish') {
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    const isAdmin = checkAuthor(req.session.role)
    if (isAdmin) return isAdmin
    try {
      await publish(req.body, req.session.username)
      return new SuccessModel('发布成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 更新项目
  if (req.method === 'POST' && req.path === '/api/item/update') {
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    const isAdmin = checkAuthor(req.session.role)
    if (isAdmin) return isAdmin
    try {
      await update(req.body, req.session.username)
      return new SuccessModel('更新成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 删除项目
  if (req.method === 'POST' && req.path === '/api/item/del') {
    const isLogin = checkLogin(req.session.username)
    if (isLogin) return isLogin
    const isAdmin = checkAuthor(req.session.role)
    if (isAdmin) return isAdmin
    try {
      await del(req.body)
      return new SuccessModel('删除成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }
}
